package com.payment.controller.payment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.payment.entity.pay.paypalpay.request.RequestPaypalPay;
import com.payment.entity.pay.paypalpay.request.RequestPaypalPayData;
import com.payment.entity.pay.paypalpay.request.RequestPaypalPayTradeData;
import com.payment.entity.pay.paypalpay.response.ResponsePaypalPay;
import com.payment.entity.pay.paypalpay.response.ResponsePaypalPayData;
import com.payment.entity.pay.paypalpay.response.ResponsePaypalPayTradeData;
import com.payment.service.SequenceService;
import com.payment.utils.MD5;
import com.payment.utils.UtilsInterfacesPackage;
import com.payment.utils.payment.PaypalConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@Api(description = "Paypal支付")
/**
 * 1，使用领科的paypal收款账号收款，Paypal支付接口：
 *
 * 2，适用于老的客户：第一版的领科商城，Travis 这种老的客户；
 *
 * 3，更新的数据表为：user_order_payment_manager_t；
 *
 *  4，更新的数据库为：links
 *
 * @author lm
 * @date 2019/11/06
 */
public class PayPalPaymentController {

    private static Logger logger = Logger.getLogger(PayPalPaymentController.class);

    @Autowired
    private SequenceService sequenceService;

    @RequestMapping(value = "/paypalpay", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @CrossOrigin
    @ResponseBody
    @ApiOperation(value = "Paypal支付下单", response = ResponsePaypalPay.class)
    public String paypalPay(@ApiParam @RequestBody RequestPaypalPay requestPaypalPay, HttpServletRequest request) throws Exception {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3，定义回报报文
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestPaypalPay);
        if (requestStr == null) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求报文是：" + requestStr);
            RequestPaypalPay requestPackage = JSONArray.parseObject(requestStr, RequestPaypalPay.class);
            String requestSign = requestPackage.getSign();
            if (requestSign == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestPaypalPayData requestData = requestPackage.getData();
                if (requestData == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    RequestPaypalPayTradeData requestTradeData = requestData.getTradeData();
                    if (requestTradeData == null || partnerCode == null || ConnSeqNo == null || tradeTime == null || token == null || tradeType == null || lang == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String orderId = requestTradeData.getOrderId();
                        String amount = requestTradeData.getAmount();
                        String mode = requestTradeData.getMode();
                        if (orderId == null || orderId == "" || amount == null || amount == "") {
                            logger.info("请求报文不合法:orderId和amount不可以为空！");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                //给前端准备需要的数据：
                                ResponsePaypalPayTradeData responseTradeData = new ResponsePaypalPayTradeData();
                                responseTradeData.setOrderId(orderId);
                                if (mode == null || mode == "" || mode.equals("production")) {
                                    responseTradeData.setClientId(PaypalConstants.production_ClientId);
                                    responseTradeData.setClientSecret(PaypalConstants.production_ClientSecret);
                                    responseTradeData.setMode("production");
                                } else {
                                    responseTradeData.setClientId(PaypalConstants.sanbox_ClientId);
                                    responseTradeData.setClientSecret(PaypalConstants.sanbox_ClientSecret);
                                    responseTradeData.setMode("sandbox");
                                }
                                //准备data
                                ResponsePaypalPayData data = new ResponsePaypalPayData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(responseTradeData);

                                ResponsePaypalPay responseWeiXinPay = new ResponsePaypalPay();
                                responseWeiXinPay.setData(data);
                                responseWeiXinPay.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(responseWeiXinPay);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;

                            }
                        }
                    }
                }
            }
        }
    }
}
